//
//  OTAddGroupViewController.m
//  OT_OC
//
//  Created by yunmian on 2019/7/15.
//  Copyright © 2019 James. All rights reserved.
//

#import "OTAddGroupViewController.h"

#import "OTEditGroupViewController.h"
#import "OTCalenderViewController.h"

#import "OTDateItemCell.h"
#import "OTAddEmployeeHeaderView.h"
#import "OTAddEmployeeFooterView.h"

#import "OTGroupModel.h"
#import "OTAddEmployeeModel.h"
#import "OTEmployeeModel.h"
#import "CalenderOTModel.h"
#import "OTMainModel.h"

@interface OTAddGroupViewController ()<UITableViewDelegate, UITableViewDataSource, OTAddEmployeeFooterViewDelegate, OTDateItemCellDelegate, OTEditGroupViewControllerDelegate, OTCalenderViewControllerDelegate, OTAddEmployeeHeaderViewDelegate>
{
    NSMutableArray              *datasource;
    UITableView                 *tableView;
    NSArray                     *OTDateStore;
}
@property (nonatomic, strong) OTEmployeeModel *employeeModel;
@property (nonatomic, copy) NSString *groupName;
@end

@implementation OTAddGroupViewController

- (instancetype)initWithParams:(NSDictionary *)params {
    self = [super init];
    if (self) {
        _employeeModel = params[@"employee"];
        _groupName = params[@"groupName"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self initData];
}

- (void)initUI {
    self.view.backgroundColor = UIColor.whiteColor;
    
    OTNavBar *navBar = [OTNavBar createNavBar];
    navBar.title = @"添加员工";
    navBar.type = OTNavBarTypeDefault;
    [self.view addSubview:navBar];
    
    OTAddEmployeeFooterView *footerView = [[OTAddEmployeeFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    footerView.delegate = self;
    
    tableView = [[UITableView alloc] init];
    tableView.backgroundColor = UIColor.whiteColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.tableFooterView = footerView;
    [tableView registerClass:[OTDateItemCell class] forCellReuseIdentifier:@"OTDateItemCell"];
    [self.view addSubview:tableView];
}

- (void)initData {
    datasource = [NSMutableArray arrayWithCapacity:5];
    
    NSString *jsonStr = @"[{\"title\":\"项目组\",\"text\":\"\",\"placeholder\":\"\",\"type\":1},{\"title\":\"姓名\",\"text\":\"\",\"placeholder\":\"请输入姓名\",\"type\":0},{\"title\":\"加班时长\",\"text\":\"\",\"placeholder\":\"\",\"type\":4},{\"title\":\"已使用\",\"text\":\"\",\"placeholder\":\"\",\"type\":2},{\"title\":\"剩余\",\"text\":\"\",\"placeholder\":\"\",\"type\":3}]";
    
    if (self.employeeModel) {
        jsonStr = [NSString stringWithFormat:@"[{\"title\":\"项目组\",\"text\":\"\%@\",\"placeholder\":\"\",\"type\":1},{\"title\":\"姓名\",\"text\":\"\%@\",\"placeholder\":\"请输入姓名\",\"type\":0},{\"title\":\"加班时长\",\"text\":\"\%@\",\"placeholder\":\"\",\"type\":4},{\"title\":\"已使用\",\"text\":\"\%@\",\"placeholder\":\"\",\"type\":2},{\"title\":\"剩余\",\"text\":\"\%@\",\"placeholder\":\"\",\"type\":3}]",self.groupName,self.employeeModel.username,self.employeeModel.totalTime,self.employeeModel.useTime,self.employeeModel.remainTime];
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:NSJSONReadingMutableContainers
                                                     error:&err];
    for (NSInteger i = 0; i < arr.count; i++) {
        OTAddEmployeeModel *model = [OTAddEmployeeModel yy_modelWithJSON:arr[i]];
        model.index = i;
        [datasource addObject:model];
    }
    
    [tableView reloadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(k_Height_NavBar, 0, 0, 0));
    }];
}

#pragma mark UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    OTAddEmployeeModel *model = datasource[section];
    return model.OTDates.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OTDateItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OTDateItemCell" forIndexPath:indexPath];
    cell.delegate = self;
    
    OTAddEmployeeModel *model = datasource[indexPath.section];
    CalenderOTModel *oModel = model.OTDates[indexPath.row];
    cell.model = oModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    OTAddEmployeeHeaderView *headerView = [[OTAddEmployeeHeaderView alloc] init];
    headerView.delegate = self;
    OTAddEmployeeModel *model = datasource[section];
    headerView.model = model;
    
    return headerView;
}

#pragma mark OTAddEmployeeFooterViewDelegate
- (void)footerViewDidSelected {
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    
    OTAddEmployeeModel *model0 = datasource[0];
    OTAddEmployeeModel *model1 = datasource[1];
    OTAddEmployeeModel *model2 = datasource[2];
    OTAddEmployeeModel *model3 = datasource[3];
    OTAddEmployeeModel *model4 = datasource[4];
    
    NSString *groupName = nilChange(model0.text) ;
    NSString *name = nilChange(model1.text);
    NSString *totalTime = nilChange(model2.text);
    NSString *useTime = nilChange(model3.text);
    NSString *remainTime = nilChange(model4.text);
    
    if ([OTTool isStringEmptyWithText:groupName]) {
        [OTTool showToastWithText:@"请选择项目组"];
        return;
    }else if ([OTTool isStringEmptyWithText:name]) {
        [OTTool showToastWithText:@"请输入姓名"];
        return;
    }else if ([OTTool isStringEmptyWithText:totalTime]) {
        [OTTool showToastWithText:@"请输入加班时长"];
        return;
    }
    
    
    
//    NSString *where = [NSString stringWithFormat:@"where %@='%@'",bg_sqlKey(@"groupName"),groupName];
//    NSArray *oldData = [OTGroupModel bg_find:ot_tablename where:where];
    
    NSMutableArray *dateArray = [NSMutableArray array];
    NSMutableArray *durationArray = [NSMutableArray array];
    
    for (CalenderOTModel *model in OTDateStore) {
        [dateArray addObject:model.OTDate];
        [durationArray addObject:model.OTDuration];
    }
    
    NSString *dateStr = [dateArray componentsJoinedByString:@","];
    NSString *durationStr = [durationArray componentsJoinedByString:@","];
    
//    if (![OTTool isArrayEmptyWithArray:oldData]) {
//        OTGroupModel *oldGroup = oldData.firstObject;
//        NSMutableArray *tempArray = [NSMutableArray array];
//        [tempArray setArray:oldGroup.list];
//
//
//        OTEmployeeModel *employee = [OTEmployeeModel new];
//        employee.name = name;
//        employee.totalTime = totalTime;
//        employee.useTime = useTime;
//        employee.remainTime = remainTime;
//        employee.OTDatas = OTDateStore;
//        [tempArray addObject:employee];
//
//        oldGroup.list = tempArray;
//
//        OTGroupModel *newGroup = [OTGroupModel new];
//        newGroup.groupName = oldGroup.groupName;
//        newGroup.list = tempArray;
//        newGroup.bg_tableName = ot_tablename;
//
//        NSString *updateWhere = [NSString stringWithFormat:@"where %@='%@'",bg_sqlKey(@"groupName"),groupName];
//        if ([newGroup bg_updateWhere:updateWhere]) {
//
//        }else {
//            [OTTool showToastWithText:@"添加失败~"];
//        }
//    }else {
//        OTGroupModel *group = [OTGroupModel new];
//        group.groupName = groupName;
//
//        OTEmployeeModel *employee = [OTEmployeeModel new];
//        employee.name = name;
//        employee.totalTime = totalTime;
//        employee.useTime = useTime;
//        employee.remainTime = remainTime;
//        employee.OTDatas = OTDateStore;
//
//        group.list = @[employee];
//
//        group.bg_tableName = ot_tablename;
//        [group bg_saveOrUpdate];
        
        OTMainModel *model = [OTMainModel new];
        model.groupName = groupName;
        model.username = name;
        model.totalTime = totalTime;
        model.useTime = useTime;
        model.remainTime = remainTime;
        model.OTDate = dateStr;
        model.OTDuration = durationStr;
        
//        model.bg_tableName = ot_tablename;
    
//        [model bg_saveOrUpdate];
//    }
    
    if ([self.delegate respondsToSelector:@selector(addGroupFinish)]) {
        [self.delegate addGroupFinish];
    }
    
    [self zw_toLastViewController];
}

#pragma mark OTAddEmployeeHeaderView
- (void)textFieldDidChange {
    OTAddEmployeeModel *model2 = datasource[2];
    OTAddEmployeeModel *model3 = datasource[3];
    OTAddEmployeeModel *model4 = datasource[4];
    
    if (![OTTool isStringEmptyWithText:model3.text]) {
        double totalTime = [model2.text doubleValue];
        double useTime = [model3.text doubleValue];
        
        if (useTime > totalTime) {
            [OTTool showToastWithText:@"不能大于总时长哦~"];
        }else {
            double remainTime = totalTime - useTime;
            NSString *remainStr = [NSString stringWithFormat:@"%.3f",remainTime];
            model4.text = [OTTool trimNumStrWithText:remainStr];
        }
        
    }else {
        model4.text = model2.text;
    }
    [tableView reloadData];
}

- (void)addEmployeeDidSelectedGroup:(OTAddEmployeeModel *)model {
    if (model.type == OTAddEmployeeModelTypeOT) {
        OTCalenderViewController *vc = [[OTCalenderViewController alloc] init];
        vc.OTDates = OTDateStore;
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        OTEditGroupViewController *vc = [OTEditGroupViewController new];
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark OTDateItemCellDelegate
- (void)OTDateItemDidSelected:(OTDateItemCell *)cell {
    
}

#pragma mark OTEditGroupViewController
- (void)editGroupDidSelectedGroup:(NSString *)groupName {
    OTAddEmployeeModel *model0 = datasource[0];
    model0.text = groupName;
    [tableView reloadData];
}

#pragma mark OTCalenderViewControllerDelegate
- (void)calenderViewDidSelectedDates:(NSArray *)dates {
    
    OTAddEmployeeModel *model = datasource[2];
    if (model.type != OTAddEmployeeModelTypeOT) {
        return;
    }
    
    NSInteger total = 0;
    for (CalenderOTModel *cModel in dates) {
        total += [cModel.OTDuration integerValue];
    }
    model.text = [NSString stringWithFormat:@"%ld",total];
    model.OTDates = dates;
    OTDateStore = dates;
//    [tableView reloadData];
    
    [self textFieldDidChange];
}

@end
